/**
 * Copyright (c) 2005-2016, yinwer81 (yinwer81@aliyun.com)
 *
 * Licensed under the Apache License, Version 2.0
 */
package com.nozturn.throne.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.kisso.common.encrypt.SaltEncoder;
import com.baomidou.kisso.common.util.RandomUtil;
import com.nozturn.throne.dao.UserDao;
import com.nozturn.throne.entity.User;
import com.nozturn.throne.service.UserService;

@Transactional
@Service
public class UserServiceImpl implements UserService {

    // private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    public User createUser(final User user) {
        user.setSalt(RandomUtil.getCharacterAndNumber(10));
        user.setPassword(SaltEncoder.md5SaltEncode(user.getSalt(), user.getPassword()));
        User persistedUser = userDao.createUser(user);
        return persistedUser;
    }

    public int updateUser(final User user) {
        int updated = userDao.updateUser(user);

        return updated;
    }

    public int changePassword(final Long pk, final String newPassword) {
        User user = userDao.findOne(pk);
        user.setSalt(RandomUtil.getCharacterAndNumber(10));
        user.setPassword(SaltEncoder.md5SaltEncode(user.getSalt(), newPassword));
        return userDao.updateUser(user);
    }

    public User findOne(final Long userId) {
        return userDao.findOne(userId);
    }

    public List<User> findAll() {
        return userDao.findAll();
    }

    public boolean verifyUser(final String salt, final String password, final String encryptpwd) {
        return SaltEncoder.md5SaltValid(salt, encryptpwd, password);
    }

    public int deleteUser(final Long pk) {
        return userDao.deleteUser(pk);
    }

    public List<User> findByUser(final User user) {
        return userDao.findByUser(user);
    }

    public User findByUsername(final String username) {
        return userDao.findByUsername(username);
    }

}
